using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.Win32;
using TXLooker.Common;
using TXLooker.WorkItemExtention.Core;
using TXLooker.WorkItemExtention.Properties;

namespace TXLooker.WorkItemExtention.UI
{
    public enum SortDirection
    {
        [Description("desc")]
        Descending = 1,
        [Description("asc")]
        Ascending = 0,
        [Description("none")]
        None = 2
    }

    public partial class WIQLViewForm : Form
    {
        private WIObject SelectedObject
        {
            get { return m_tfsTreeCtrl.SelectedObject; }
        }

        public Guid GuidNodeExpand { get; set; }

        private readonly QueryTextBuilder builder = new QueryTextBuilder();

        public delegate void ApplyChangesEventHandler();
        public event ApplyChangesEventHandler ChangesApplied;

        public WIQLViewForm()
        {
            InitializeComponent();
        }

        private void Initialize()
        {
            m_tfsTreeCtrl.LoadF();
            m_tfsTreeCtrl.SelectionChanged += OnTreeSelectionChanged;
            btnApply.Enabled = false;
        }

        private void ApplyChanges()
        {
            if (btnApply.Enabled == false)
                return;

            if (SelectedObject == null) return;
            var query = SelectedObject as WIStoredQuery;
            if (query == null) return;
            var TFSStoredQuery = query.GetQuery();
            if (TFSStoredQuery == null) return;

            try
            {
                var newQueryText = builder.GetQueryText();
                var newColumnsWidths = builder.GetColumnWidths();
                query.NeedRefresh = true;
                TFSStoredQuery.QueryText = newQueryText;
                TFSStoredQuery.Update();
                SaveColumnWidthsInRegistry(newColumnsWidths);
                ChangesApplied();

            }
            catch (InvalidQueryTextException ex)
            {
                LogManager.WriteMessageToCustomLog(ex);
            }
            catch (UnauthorizedAccessException ex)
            {
                MessageBox.Show(ex.Message);
            }

            btnApply.Enabled = false;
        }

        private void SaveColumnWidthsInRegistry(string columnsWidths)
        {
            var selObject = SelectedObject;
            if (selObject == null)
                return;
            var key = Resources.REGISTRY_FULL_PATH;
            var keyColumnsWidths = Registry.CurrentUser.OpenSubKey(Resources.REGISTRY_RELATIVE_PATH);


            if (keyColumnsWidths == null)
                return;

            var storedQuery = selObject as WIStoredQuery;
            if (storedQuery == null)
                return;
            var queryID = storedQuery.QueryGuid.ToString();

            Registry.SetValue(key, queryID, columnsWidths, RegistryValueKind.String);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Initialize();
        }

        private void OnTreeSelectionChanged(object sender, EventArgs args)
        {
            var selObject = SelectedObject;
            if (selObject == null) return;

            switch (selObject.Type)
            {
                case WIObjectType.Server:
                case WIObjectType.Project:
                case WIObjectType.QueriesRoot:
                case WIObjectType.QueriesGroup:
                    {
                        m_queryViewPanel.Enabled = false;
                    }
                    break;
                case WIObjectType.Query:

                    m_queryViewPanel.Enabled = true;

                    var crsr = Cursor;
                    Cursor = Cursors.WaitCursor;

                    try
                    {
                        var storedQuery = selObject as WIStoredQuery;
                        if (storedQuery == null) return;
                        var squery = storedQuery.GetQuery();

                        builder.InitBuilder(squery);

                        lbSourceColumns.DataSource = builder.SourceColumns;
                        lbSourceColumns.DisplayMember = "ColumnHeaderText";
                        lbTargetColumns.DataSource = builder.TargetColumns;
                        lbTargetColumns.DisplayMember = "ColumnHeaderText";
                        SetTextBoxInfoValue();
                        btnApply.Enabled = false;

                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.ToString());
                    }
                    finally
                    {
                        Cursor = crsr;
                    }
                    break;
            }
        }

        private void OnUpFieldClick(object sender, EventArgs e)
        {
            var columnInd = lbTargetColumns.SelectedIndex;
            if (columnInd < 1) return;
            builder.MoveColumnUp(lbTargetColumns.SelectedIndex);
            lbTargetColumns.SelectedIndex = columnInd - 1;
            btnApply.Enabled = true;
        }

        private void OnDownFieldClick(object sender, EventArgs e)
        {
            var columnInd = lbTargetColumns.SelectedIndex;
            if (columnInd >= lbTargetColumns.Items.Count - 1) return;
            builder.MoveColumnDown(lbTargetColumns.SelectedIndex);
            lbTargetColumns.SelectedIndex = columnInd + 1;
            btnApply.Enabled = true;
        }

        private void OnOKClick(object sender, EventArgs e)
        {
            ApplyChanges();
        }

        private void OnCancelClick(object sender, EventArgs e)
        {
        }

        private void OnApplyClick(object sender, EventArgs e)
        {
            ApplyChanges();
        }

        private void OnWidthTextChanged(object sender, EventArgs e)
        {
            builder.TargetColumns[lbTargetColumns.SelectedIndex].Width = tbWidth.Text;
            btnApply.Enabled = true;
        }

        private void OnSourceColumnsDoubleClick(object sender, EventArgs e)
        {
            builder.AddColumn(lbSourceColumns.SelectedIndex);
            btnApply.Enabled = true;
        }

        private void OnSourceColumnsKeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    builder.AddColumn(lbSourceColumns.SelectedIndex);
                    btnApply.Enabled = true;
                    break;
                case Keys.Space:
                    builder.AddColumn(lbSourceColumns.SelectedIndex);
                    btnApply.Enabled = true;
                    break;
            }
        }

        private void OnTargetColumnsDoubleClick(object sender, EventArgs e)
        {
            builder.RemoveColumn(lbTargetColumns.SelectedIndex);
            btnApply.Enabled = true;
        }

        private void OnTargetColumnsKeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    builder.RemoveColumn(lbTargetColumns.SelectedIndex);
                    btnApply.Enabled = true;
                    break;
                case Keys.Space:
                    builder.RemoveColumn(lbTargetColumns.SelectedIndex);
                    btnApply.Enabled = true;
                    break;
            }

        }

        private void OnAddButtonClick(object sender, EventArgs e)
        {
            builder.AddColumn(lbSourceColumns.SelectedIndex);
            btnApply.Enabled = true;
        }

        private void OnRemoveButtonClick(object sender, EventArgs e)
        {
            builder.RemoveColumn(lbTargetColumns.SelectedIndex);
            btnApply.Enabled = true;
        }

        private void OnTargetColumnsSelectedValueChanged(object sender, EventArgs e)
        {
            SetTextBoxInfoValue();
        }

        private void SetTextBoxInfoValue()
        {
            var curInd = lbTargetColumns.SelectedIndex;
            if (curInd >= 0)
                tbWidth.Text = builder.TargetColumns[curInd].Width;
        }

        private void OnTextBoxWidthFocusEnter(object sender, EventArgs e)
        {
            btnApply.Enabled = true;
        }
    }
}